package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.Barrels;
import Models.BarrelList;

public class BarrelListPresenter extends AbstractPresenter<BarrelList> {
	final String SINGLEITEM = "barrelList";
	final String MULTIITEM = "barrelLists";
	
	public ArrayList<BarrelList> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public BarrelList tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public BarrelList createItemFromJSONObject(JSONObject jsonObject){
		BarrelList item = new BarrelList();
		try{
			//Set Inventory Usage Collection
			ArrayList<Barrels> barrels = new ArrayList<Barrels>();
			if(!jsonObject.isNull("barrels")){
				Object itm = jsonObject.get("barrels");
				BarrelsPresenter presenter = new BarrelsPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						barrels.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					barrels.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setBarrelCollection(barrels);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(BarrelList item){
		try{
			JSONObject json = new JSONObject();
			//Create Doc Collection
			if(item.getBarrelCollection()!=null){
				BarrelsPresenter presenter = new BarrelsPresenter();
				if(item.getBarrelCollection().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getBarrelCollection().size(); i++){
						jsonArray.put(presenter.createJSON(item.getBarrelCollection().get(i)));
					}
					json.put("barrels", jsonArray);
				}
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public BarrelList getEmptyEntity(){
		BarrelList entity = new BarrelList();
		return entity;
	}
}
